// from gozero logx.rotatelogger.go
package alog

import (
	"fmt"
	"path/filepath"
	"time"
)

const (
	dateFormat  = "2006-01-02"
	hoursPerDay = 24
)

type RotateRule interface {
	BackupFileName() string
	MarkRotated()
	OutdatedFiles() []string
	ShallRotate(size int64) bool
}

type DailyRotateRule struct {
	filename    string
	days        int
	rotatedTime string
}

func getNowDate() string {
	return time.Now().Format(dateFormat)
}

func CreateDailyRotateRule(filename string, days int) RotateRule {
	return &DailyRotateRule{
		filename:    filename,
		days:        days,
		rotatedTime: getNowDate(),
	}
}

func (r *DailyRotateRule) BackupFileName() string {
	return fmt.Sprintf("%s.%s", r.filename, getNowDate())
}

func (r *DailyRotateRule) MarkRotated() {
	r.rotatedTime = getNowDate()
}

func (r *DailyRotateRule) OutdatedFiles() []string {
	if r.days <= 0 {
		return nil
	}

	parttern := fmt.Sprintf("%s*", r.filename)

	files, err := filepath.Glob(parttern)
	if err != nil {
		return nil
	}

	boundary := time.Now().Add(-time.Hour * time.Duration(hoursPerDay*r.days)).Format(dateFormat)
	boundaryFile := r.filename + "." + boundary

	var outdates []string
	for _, file := range files {
		if file < boundaryFile {
			outdates = append(outdates, file)
		}
	}

	return outdates
}

func (r *DailyRotateRule) ShallRotate(_ int64) bool {
	return len(r.rotatedTime) > 0 && getNowDate() != r.rotatedTime
}
